#include "ScreenshotService.h"
#include "log.h"
#include <QClipboard>
#include <QDateTime>
#include <QDir>
#include <QFileInfo>
#include <QStandardPaths>
#include <QPainter>

ScreenshotService::ScreenshotService(QObject *parent)
    : QObject(parent)
{
    logInfo("ScreenshotService 初始化完成");
}

ScreenshotService::~ScreenshotService()
{
    logInfo("ScreenshotService 销毁");
}

ScreenshotService& ScreenshotService::instance()
{
    static ScreenshotService instance;
    return instance;
}

QPixmap ScreenshotService::captureAllScreens()
{
    QPixmap fullPixmap;
    
    // 获取所有屏幕
    QList<QScreen*> screens = QApplication::screens();
    
    if (screens.isEmpty()) {
        logError("没有找到屏幕");
        return QPixmap();
    }
    
    // 计算所有屏幕的总区域
    QRect totalRect;
    for (QScreen* screen : screens) {
        QRect screenGeometry = screen->geometry();
        totalRect = totalRect.united(screenGeometry);
    }
    
    // 创建全屏截图
    fullPixmap = QPixmap(totalRect.size());
    fullPixmap.fill(Qt::black);
    
    QPainter painter(&fullPixmap);
    for (QScreen* screen : screens) {
        QPixmap screenPixmap = screen->grabWindow(0);
        QRect screenGeometry = screen->geometry();
        painter.drawPixmap(screenGeometry.x() - totalRect.x(),
                          screenGeometry.y() - totalRect.y(),
                          screenPixmap);
    }
    
    logInfo("全屏截图完成 - 尺寸: " << fullPixmap.width() << "x" << fullPixmap.height());
    return fullPixmap;
}

QPixmap ScreenshotService::captureScreen(QScreen* screen)
{
    if (!screen) {
        logError("屏幕对象为空");
        return QPixmap();
    }
    
    QPixmap pixmap = screen->grabWindow(0);
    logInfo("屏幕截图完成 - 尺寸: " << pixmap.width() << "x" << pixmap.height());
    return pixmap;
}

QPixmap ScreenshotService::captureRegion(const QRect& rect)
{
    if (rect.isEmpty()) {
        logError("截图区域为空");
        return QPixmap();
    }

    // 获取全屏截图
    QPixmap fullPixmap = captureAllScreens();
    if (fullPixmap.isNull()) {
        logError("无法获取全屏截图");
        return QPixmap();
    }

    // 计算所有屏幕的总区域
    QRect totalRect;
    QList<QScreen*> screens = QApplication::screens();
    for (QScreen* screen : screens) {
        totalRect = totalRect.united(screen->geometry());
    }

    // 调整区域坐标（相对于总区域）
    QRect adjustedRect = rect;
    adjustedRect.translate(-totalRect.x(), -totalRect.y());

    // 确保区域在截图范围内
    adjustedRect = adjustedRect.intersected(fullPixmap.rect());

    if (adjustedRect.isEmpty()) {
        logError("调整后的截图区域为空");
        return QPixmap();
    }

    // 截取区域
    QPixmap regionPixmap = fullPixmap.copy(adjustedRect);
    logInfo("区域截图完成 - 区域: " << rect.width() << "x" << rect.height());
    return regionPixmap;
}

/**
 * @brief [FDD-2025-03-021][API-004] 优化的区域截图方法
 * 按屏幕交集抓取，避免构建整屏 QPixmap，直接写入目标区域
 * @param rect 全局坐标区域
 * @return 区域截图（QImage）
 */
QImage ScreenshotService::captureRegionOptimized(const QRect& rect)
{
    if (rect.isEmpty()) {
        logError("[E020_INVALID_RECT] 截图区域为空");
        return QImage();
    }

    QList<QScreen*> screens = QApplication::screens();
    if (screens.isEmpty()) {
        logError("[E020_NO_SCREENS] 没有找到屏幕");
        return QImage();
    }

    // 创建目标 QImage（只分配需要的大小）
    QImage resultImage(rect.size(), QImage::Format_RGB32);
    resultImage.fill(Qt::black);

    QPainter painter(&resultImage);
    bool hasIntersection = false;

    // 遍历所有屏幕，只抓取与目标区域相交的部分
    for (QScreen* screen : screens) {
        QRect screenGeometry = screen->geometry();
        QRect intersection = rect.intersected(screenGeometry);

        if (intersection.isEmpty()) {
            continue; // 该屏幕与目标区域不相交，跳过
        }

        hasIntersection = true;

        // 计算该屏幕内的相对坐标
        QRect screenLocalRect = intersection.translated(-screenGeometry.topLeft());

        // 抓取该屏幕的交集区域（使用 grabWindow）
        // 注意：QScreen::grabWindow(0) 抓取整个屏幕，我们需要手动裁剪
        QPixmap screenPixmap = screen->grabWindow(0);
        QImage screenImage = screenPixmap.toImage();

        // 裁剪出交集部分
        QImage croppedImage = screenImage.copy(screenLocalRect);

        // 计算在目标 QImage 中的绘制位置
        QPoint destPos = intersection.topLeft() - rect.topLeft();

        // 将裁剪后的图像绘制到目标位置
        painter.drawImage(destPos, croppedImage);

        qDebug() << "[CaptureOptimized] Screen" << screens.indexOf(screen)
                 << "intersection:" << intersection
                 << "screenLocal:" << screenLocalRect
                 << "destPos:" << destPos;
    }

    painter.end();

    if (!hasIntersection) {
        logError("[E020_NO_INTERSECTION] 目标区域与所有屏幕都不相交");
        return QImage();
    }

    logInfo("[CaptureOptimized] 优化截图完成 - 区域: " << rect.width() << "x" << rect.height()
            << " 内存占用约: " << (resultImage.sizeInBytes() / 1024) << " KB");

    return resultImage;
}

bool ScreenshotService::saveScreenshot(const QPixmap& pixmap, const QString& filePath)
{
    if (pixmap.isNull()) {
        logError("截图为空，无法保存");
        emit screenshotSaveFailed("截图为空");
        return false;
    }
    
    QString savePath = filePath;
    
    // 如果路径为空，使用默认路径和文件名
    if (savePath.isEmpty()) {
        QString defaultPath = getDefaultSavePath();
        QString fileName = generateDefaultFileName();
        QString format = m_config.getDefaultFormat();
        savePath = QDir(defaultPath).filePath(fileName + "." + format);
    }
    
    // 确保目录存在
    QFileInfo fileInfo(savePath);
    QDir dir = fileInfo.absoluteDir();
    if (!dir.exists() && !dir.mkpath(dir.absolutePath())) {
        QString error = QString("无法创建目录: %1").arg(dir.absolutePath());
        logError(error);
        emit screenshotSaveFailed(error);
        return false;
    }
    
    // 保存文件
    bool success = false;
    QString format = QFileInfo(savePath).suffix().toLower();
    
    if (format == "jpg" || format == "jpeg") {
        // JPEG 格式，使用质量设置
        success = pixmap.save(savePath, "JPEG", m_config.getJpegQuality());
    } else {
        // PNG 或其他格式
        success = pixmap.save(savePath);
    }
    
    if (success) {
        logInfo("截图已保存: " << savePath);
        emit screenshotSaved(savePath);
        return true;
    } else {
        QString error = QString("保存截图失败: %1").arg(savePath);
        logError(error);
        emit screenshotSaveFailed(error);
        return false;
    }
}

void ScreenshotService::copyToClipboard(const QPixmap& pixmap)
{
    if (pixmap.isNull()) {
        logError("截图为空，无法复制到剪贴板");
        return;
    }
    
    QClipboard* clipboard = QApplication::clipboard();
    clipboard->setPixmap(pixmap);
    logInfo("截图已复制到剪贴板");
}

QString ScreenshotService::getDefaultSavePath() const
{
    QString path = m_config.getDefaultSavePath();
    if (path.isEmpty()) {
        // 使用系统默认的图片目录
        path = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
    }
    return path;
}

QString ScreenshotService::generateDefaultFileName() const
{
    QString templateStr = m_config.getDefaultFileName();
    if (templateStr.isEmpty()) {
        templateStr = "Screenshot_%1";
    }
    
    // 替换 %1 为当前时间戳
    QString timestamp = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss");
    return templateStr.arg(timestamp);
}

